import { Ref, watch } from "vue";
import { patrolingControl } from "@/api/cruise.js";
import { modes } from "../shared";

/*
 * @Author: ReinerLau lk850593913@gmail.com
 * @Date: 2023-01-31 15:12:55
 * @LastEditors: ReinerLau lk850593913@gmail.com
 * @LastEditTime: 2023-01-31 15:23:10
 * @FilePath: \v2.0.0\src\views\patroling\composables\useCarMove.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
interface carMoveOptions {
  speed: Ref<number>;
  direction: Ref<number>;
  caritem: Ref<string>;
  mode: Ref<number>;
}

export default (options: carMoveOptions) => {
  const { speed, direction, caritem, mode } = options;
  let st = null;
  let seq = 0;

  function submitData() {
    const data = { x: speed.value, y: direction.value, seq };
    patrolingControl(caritem.value, data).then(() => {
      seq++;
      if (seq > 254) {
        seq = 0;
      }
      // 按住按钮的情况
      if (speed.value !== 0 || direction.value !== 0) {
        st = setTimeout(submitData, 200);
      }
    });
  }

  watch([speed, direction], () => {
    if (mode.value !== modes.MANUAL) return;
    clearTimeout(st);
    submitData();
  });
};
